package org.itboys.mobile.service.pos;


import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.json.JsonUtils;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.kitchen.dao.order.KitchenOrderMapper;
import org.itboys.kitchen.entity.mysql.order.KitchenOrder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.pos.income.PosIncomeResult;
import org.itboys.mobile.entity.pos.member.PosMember;
import org.itboys.mobile.entity.pos.member.PosMemberResult;
import org.itboys.mobile.entity.pos.sale.PosSale;
import org.itboys.mobile.entity.pos.sale.PosSaleResult;
import org.itboys.mobile.entity.pos.score.PosScoreResult;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mobile.service.pos.util.PosHttpHelper;
import org.itboys.mobile.service.pos.util.PosMD5Util;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.DatetUtil;
import org.itboys.mobile.util.ResponseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.Sun;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 作者：jiangxiong
 * 日期：2016年7月8日
 * 联系方式 ：empty90911@126.com
 * 描述：花果山_pos_销售额统计
 */
@Service
public class PosSaleService {
	private final static Logger logger = LoggerFactory.getLogger(PosHttpHelper.class);


	@Autowired
	private KitchenOrderMapper orderMapper;
	@Autowired
	private SundayMemberService memberService;
	@Autowired
	private SystemDictionaryService dictionaryService;

	/**
	 * 
	 * 查询单个会员信息（会返回余额和积分）
	 * 
	 * 会员卡状态：0未发卡,1已发卡,8挂失,9作废
	 * **/
	public  static List<PosSale> getPosSaleFromPos(String BranchCode,String BeginDate,String EndDate) {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("Method", "GetLSOrder");
		//时间搓
		Long timeStamp = new Date().getTime();
		param.put("TimeStamp", timeStamp);
		//	Integer Page =1;
		//参数

		String data = "{\"BranchCode\":\"" + BranchCode + "\",\"BeginDate\":\"" + BeginDate + "\",\"EndDate\":\"" + EndDate+"\"}";
		//签名
		logger.info("--pos-查询销售报表-参数"+data);
		String Signature = PosMD5Util.MD5(PosCommons.token + timeStamp + data);
		param.put("data", data);
		param.put("Signature", Signature.toUpperCase());

		String posSaleResult = PosHttpHelper.doPostWithUtf8(PosCommons.url, param);
		logger.info("--pos-查询销售报表-结果"+posSaleResult);
		PosSaleResult result=  JsonUtils.jsonToObject(PosSaleResult.class, posSaleResult);
		Integer code = result.ResCode;
		if(code!=0){
			throw new ErrorException(result.Msg);
		}else{
			return result.ResData;
		}
	}
	/**
	 *统计APP和POS的今日销售数据
 	 */
	public Map<String,Object> getSale(HttpServletRequest request,Long memberId) throws Exception{
		//返回结果
		Map<String,Object> result =new HashMap<String,Object>();
		List<SundayMember> shops =new ArrayList<SundayMember>();
		Map<String,Object> param = new HashMap<String,Object>();
		//判断用户是否属于超级用户，超级用户要查询所有的图文报表

		SundayMember shop =memberService.getById(memberId);

		boolean isSuperShop=false;
		List<SystemDictionary> dictionaries =dictionaryService.getDictionaryByKey("superMobile");
		for(SystemDictionary dictionary:dictionaries){
			if(dictionary.getValue().equalsIgnoreCase(shop.getMobile())){
				isSuperShop=true;
			}
		}
		//临时代码
		//isSuperShop=true;
		if(isSuperShop){
			param.clear();
			param.put("userType", SundayCommonConstants.user_type_shop);
			param.put("isDeleted", SundayCommonConstants.NO);
			param.put("parentId",0);
			param.put("number !=","jiangxiong");
			shops=memberService.list(param);
		}else{
			if(shop.getUserType()==SundayCommonConstants.user_type_shop&&(shop.getParentId()==null||shop.getParentId().longValue()==0l)){
			shops.add(shop);
			}
		}
		if(ListUtil.isNull(shops))return result;
		//String pattern_time="yyyy-MM-dd HH:mm:ss";
		String BeginDate= request.getParameter("BeginDate");
		if(StringUtils.isNotEmpty(BeginDate)){
			BeginDate=BeginDate+" 00:00:00";
		}else{
			BeginDate=TimeUtils.formatToTime(DatetUtil.setDateStart(new Date()));

		}
		String EndDate= request.getParameter("EndDate");
		if(StringUtils.isNotEmpty(EndDate)){
			EndDate+=" 23:59:59";
		}else{
			EndDate=TimeUtils.formatToTime(DatetUtil.setDateStart(new Date()));
		}



		//获取所有门店的线上销售额订单
		param.clear();
		param.put("type",SundayCommonConstants.type_mall);
		param.put("orderStatuses", Arrays.asList(2,3,4,5));
		param.put("createTime_start",BeginDate);
		param.put("createTime_end",EndDate);
		List<KitchenOrder> orders = orderMapper.select(param);
		//返回的销售额
		List<Map<String,Object>> result_sales =new ArrayList<Map<String,Object>>();

		List<BigDecimal> result_sale_pos =new ArrayList<BigDecimal>();
		List<BigDecimal> result_sale_app =new ArrayList<BigDecimal>();
		//返回的门店
		List<String> result_shops =new ArrayList<String>();
		for(SundayMember s:shops){

			//sale.put()
			result_shops.add(s.getNickName()+"-编号："+s.getNumber());


			//线下销售额额
			Double posSaleAmount=0.00;
			if(StringUtils.isNotEmpty(s.getNumber())){
				List<PosSale> posSales= new ArrayList<>();
				try{
					posSales=getPosSaleFromPos(s.getNumber(),BeginDate,EndDate);
				}catch (Exception e){
					logger.error(e.getMessage());
					continue;
				}



				for(PosSale posSale:posSales){
					posSaleAmount+=posSale.PayAmt.doubleValue();
				}
			}
			result_sale_pos.add(new BigDecimal(posSaleAmount).setScale(2,BigDecimal.ROUND_HALF_UP));




			//线上销售额
			Double appSaleAmount=0.00;
			for(KitchenOrder order:orders){
				if(LongUtil.isNotZreo(order.getShopId())&&
						order.getShopId().longValue()==s.getId()){
					appSaleAmount+=order.getPayAmount().doubleValue();
					if(order.getBalancePayAmount()!=null){
							appSaleAmount+=order.getBalancePayAmount().doubleValue();
					}
				}
			}
			result_sale_app.add(new BigDecimal(appSaleAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
			logger.info("门店："+s.getNumber()+",线上="+appSaleAmount+",线下="+posSaleAmount);

		}
		result.put("shops",result_shops);
		Map<String,Object> result_sale1 = new HashMap<String,Object>();
		result_sale1.put("name","POS系统");
		result_sale1.put("data",result_sale_pos);
		Map<String,Object> result_sale2 = new HashMap<String,Object>();
		result_sale2.put("name","APP系统");
		result_sale2.put("data",result_sale_app);
		result_sales.add(result_sale1);
		result_sales.add(result_sale2);
		result.put("sales",result_sales);


		return result;
	}
	public static void main(String[] args) {
		getPosSaleFromPos("00010001","2017-08-28","2017-08-29");

	}
  }
